pipeline {
    agent any

    environment {
        ENVIRONMENT = 'cfhy-test'
        REQUEST_ENVIR = 'jacoco-test'
        gitRepositoryUrl = "https://git.cfhy.work/test/api_interface.git"
        credentialsId = "0f305fa1-acba-4c0a-9bdf-cdd66f4ea128"
    }
    parameters {
        gitParameter(
            branch: '',
            branchFilter: ".*",
            defaultValue: "origin/master",
            description: '',
            listSize: '10',
            name: 'GIT_BRANCHES',
            quickFilterEnabled: false,
            selectedValue: 'NONE',
            sortMode: 'ASCENDING_SMART',
            tagFilter: "*",
            type: 'Branch',
            useRepository: 'https://git.cfhy.work/test/api_interface.git')
        string(name: 'projectName', defaultValue: '', description: 'The project name')
        string(name: 'branchName', defaultValue: '', description: 'The project branch name')
        string(name: 'podName', defaultValue: '', description: 'The upstream pod name')
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }
    tools {
        //maven 'apache-maven-3.6.0'
        maven 'maven'
        jdk 'JDK'
    }
    stages {
        stage('Pull autoTest code') {
            steps {
                sh "rm -rf ./* .git*"
                script {
                    dir('autoDevops'){
                        checkout poll: false, scm: [$class: 'GitSCM', branches: [[name: "${GIT_BRANCHES}"]],
                        doGenerateSubmoduleConfigurations: false,
                        extensions: [],
                        submoduleCfg: [],
                        userRemoteConfigs: [[credentialsId: "${credentialsId}", url: "${gitRepositoryUrl}"]]]
                    }
                }
            }
        }
        stage('clean memory dump data') {
            steps {
                script {
                    def projects = [
                        [projectName: "${projectName}", nowVersion: "${branchName}",environment: ENVIRONMENT],
                        // [projectName: 'admin-center', nowVersion: 'origin/dev/2023.10',environment: ENVIRONMENT],
                    ]

                    def requestBody = [param: projects]
                    def json = groovy.json.JsonOutput.toJson(requestBody)
                    echo "json: ${json}"

                    def cleanMemoryDumpUrl = "https://${REQUEST_ENVIR}.cfhy.work/jacoco-server/jacoco/cleanMemoryDump"
                    echo "cleanMemoryDumpUrl: ${cleanMemoryDumpUrl}"

                    def response = httpRequest(
                        httpMode: 'POST',
                        ignoreSslErrors: true,
                        contentType: 'APPLICATION_JSON',
                        requestBody: json,
                        url: cleanMemoryDumpUrl
                    )
                    echo "POST Request 1 Response Code: ${response.getStatus()}"
                    echo "POST Request 1 Response Body: ${response.getContent()}"
                }
            }
        }
        
        stage('check upstream pod') {
            steps {
                script {
                    sh '''
                        podNs='test01'
                        result1=$(kubectl get pod -n ${podNs} | grep ${podName} | awk '{print $2}')
                        result2=$(kubectl get pod -n ${podNs} | grep ${podName} | awk '{print $3}')
                        result3=$(kubectl get pod -n ${podNs} | grep ${podName} | awk '{print $4}')
                        if [ "$result1" == '1/1' ] && [ "$result2" == 'Running' ] && [ "$result3" == '0' ]; then
                            echo "${podNs} ${podName} update succeeded"
                        else
                            echo "${podNs} ${podName} update failed"
                            echo 'Exiting'
                            exit 1
                        fi
                    '''
                }
            }
        }

        stage('Running Test Scenario') {
            steps {
                catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') {
                    sh '''
                    java -version
                    cd autoDevops
                    mvn clean test -Dsurefire.suiteXmlFiles=testng.xml
                    '''
                }
            }
        }
        stage('get coverage report ') {
            steps {
                script {
                    def generateCoverage = { projectName, nowVersion, baseVersion ->
                        def coverageBody = [
                            projectName: projectName,
                            nowVersion: nowVersion,
			   baseVersion: baseVersion,
                            environment: ENVIRONMENT,
                            diffType: '1',
                            jenkinsBuildNumber: -1,
                            cleanMemoryDump: 1
                        ]

                        def coverageJson = groovy.json.JsonOutput.toJson(coverageBody)
                        echo "coverageJson: ${coverageJson}"

            

                        def genratorCoverUrl = "https://${REQUEST_ENVIR}.cfhy.work/jacoco-server/jacoco/generatorCover"
                        echo "genratorCoverUrl: ${genratorCoverUrl}"

                        def response = httpRequest(
                            httpMode: 'POST',
                            contentType: 'APPLICATION_JSON',
                            requestBody: coverageJson,
                            url: genratorCoverUrl,
                        )
                        echo "POST Request Response Code: ${response.getStatus()}"
                        echo "POST Request Response Code: ${response.getContent()}"
                    }

                    generateCoverage("${projectName}", "${branchName}", "origin/master")
                    // generateCoverage('admin-center', 'origin/dev/2023.10', 'origin/master')
                }
            }
        }
    }
    post{
        always{

                            
        //生成allure报告
        allure includeProperties: false, jdk: '', results: [[path: 'autoDevops/target/allure-results']]
        }
    }
}
